package com.sky.config.threadPool;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/9/23
 */
@Configuration
public class ThreadPoolConfig {

    @Bean(name = "threadPoolTaskExcutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 返回虚拟机处理器的最大数量，不小于1
        int MaxVMNum = Runtime.getRuntime().availableProcessors();
        System.out.println("可用处理器的虚拟机的最大线程数量为：" + MaxVMNum);
        int core = MaxVMNum / 3;
        System.out.println(core);
        //设置核心数
        executor.setCorePoolSize(core);
        // 设置最大线程数，最好为核心数的2N+1
        executor.setMaxPoolSize(core * 2 + 1);
        //除核心线程外的线程存活时间
        executor.setKeepAliveSeconds(20);
        // 如果传入值大于0，底层队列使用的是LinkedBlockingQueue，否则默认使用SynchronousQueue
        executor.setQueueCapacity(40);
        // 线程前缀
        executor.setThreadNamePrefix("thread-execute");
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
